package healthsolutions.wk;

import healthsolution.wk.R;
import healthsolutions.wk.HTService;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
import android.content.BroadcastReceiver;

public class HTService extends Activity  implements Runnable
{
	private static final String TAG = "HTService";
	private LocationManager mLocationManager = null;
	private TelephonyManager mTelephoneManager = null;
	//private static final int LOCATION_INTERVAL = 10000;
	//private static final float LOCATION_DISTANCE = 5.0f;
	private static final float LOCATION_DISTANCE = 0;
	////////////////// UPDATE TELA /////////////////
	//GPSData objGPSDataClass=new GPSData();
	//GPSData objGPSDataClass;
	public double dbLat=0;
	public double dbLon=0;
	public double dbAlt=0;
	public float flSpeed=0;
	public String strLevelbat=null;
	String Imei;

	public Thread currentThread = new Thread(this);
	//private Handler handler = new Handler();
	
	public HTService()
	{
		
	}
		
	public void run() {
		// TODO Auto-generated method stub
		
		Log.i(TAG, "[run] Run");									//DEBUG
		try
		{
			//Thread currentThread = new Thread(this);
		   // currentThread.start();
			
			//startUpdateCoordinates();
			//Thread.sleep(1000);			
			//Looper.prepare();
			//Looper.loop();
			threadHandler.sendEmptyMessage(0);
						
		}catch(Exception Ex)
		{
			Log.e(TAG, "[run] Error: " +Ex.getMessage());									//DEBUG
		}
		    
	}
	
	private Handler threadHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            // whenever the Thread notifies this handler we have
            // only this behavior
          //  threadModifiedText.setText("my text changed by the thread");
        	
        	startUpdateCoordinates();
        	/*while(!currentThread.isAlive())
        	{
        		startUpdateCoordinates();
        		try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        	*/
        }
    };
 
    
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		Log.e(TAG, "[onCreate] onCreate");		
		 super.onCreate(savedInstanceState);	
		// setContentView(R.layout.viewsender);
			// appContext = this.getApplicationContext();
		// Thread currentThread = new Thread(this);
		 currentThread.start();		 		
	}
	
	
	public boolean startUpdateCoordinates()
	{			
		Log.e(TAG, "[startUpdateCoordinates] startUpdateCoordinates");									//DEBUG
		try
		{	
			voSetView();
			
			 int inTiempoEnvio=0;
						 
			    SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);	    
			    try
			    {
				    initializeLocationManager();
				    
				     inTiempoEnvio=Integer.valueOf(settings.getString("Timer",null))*1000;
				     //inTiempoEnvio=1;
			    }catch(Exception ex)
			    {
			    	Log.e(TAG, "[startUpdateCoordinates] ERROR: "+ex);		
			    	//settings.edit().clear();
			    }
			    try {
			        
			    	if((inTiempoEnvio!=0))
			    	{
			    		Log.i(TAG, "[startUpdateCoordinates] inTiempoEnvio Net: "+inTiempoEnvio);		//DEBUG
			    		
			    		mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, inTiempoEnvio, LOCATION_DISTANCE,
			    				mLocationListeners[1]);
			    				//locationlistener);
			    	}else
			    	{
			    		mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,2, LOCATION_DISTANCE,
			    				//locationlistener);
				    			mLocationListeners[1]);
			    	}
			    	Log.d(TAG, "[startUpdateCoordinates] Pase REQUEST_LOCATION_UPDATES");		//DEBUG    	
			        
			    	strLevelbat=strbatteryLevel();        
			        Imei = mTelephoneManager.getDeviceId();
			        
			        
			    } catch (java.lang.SecurityException ex) {
			        Log.i(TAG, "[startUpdateCoordinates] fail to request location update, ignore", ex);		//DEBUG
			    } catch (IllegalArgumentException ex) {
			        Log.d(TAG, "[startUpdateCoordinates] network provider does not exist, " + ex.getMessage());		//DEBUG        
			    }
			  /////////////////////////////////////////////////////////////////////////
			    try {
			        
			    	if((inTiempoEnvio!=0))
			    	{
			    		Log.i(TAG, "[startUpdateCoordinates] inTiempoEnvio GPS: "+inTiempoEnvio);		//DEBUG
			    		mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, inTiempoEnvio, LOCATION_DISTANCE,
			    			//locationlistener);
			    			mLocationListeners[0]);
			    	}else
			    	{
			    		mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2, LOCATION_DISTANCE,
			    				//locationlistener);
			    				mLocationListeners[0]);
			    	}
			    	Log.d(TAG, "[startUpdateCoordinates] Pase REQUEST_LOCATION_UPDATES 2 DOS");		//DEBUG
			    	
			        Imei = mTelephoneManager.getDeviceId();      
			        strLevelbat=strbatteryLevel();
			        
			    } catch (java.lang.SecurityException ex) {
			        Log.i(TAG, "[startUpdateCoordinates] fail to request location update, ignore", ex);			//DEBUG
			    } catch (IllegalArgumentException ex) {
			        Log.d(TAG, "[startUpdateCoordinates] gps provider does not exist " + ex.getMessage());			//DEBUG
			    }
			    
			    ///////////////////////////// TIMER //////////////////////////
			       try
					{
			        	Log.i("HTService","Durmiendo el tiempo configurado TIME: "+settings.getString("Timer",null));
						Thread.sleep(Integer.valueOf(settings.getString("Timer",null))*1000,0);
					}
					catch (InterruptedException e)
					{
						Log.i("HTService","SLEEP ERROR: "+e);
					}
			     //objGPSDataClass.updateCoordinates(dbLat,dbLon,dbAlt,flSpeed,Imei,strLevelbat);
		}catch(Exception Ex)
		{
			Log.e(TAG, "[startUpdateCoordinates] ERROR: "+Ex);									//DEBUG
			return false;	
		}
		 return true;
	}
	
	///////////////////////////////////////////////////// Set View //////////////////////////////
	public void voSetView()
	{
		 SharedPreferences settings ;
     	 settings = getSharedPreferences("HT",MODE_PRIVATE);
     	 
		setContentView(R.layout.login);
		
		TextView txtImei = (TextView) findViewById(R.id.TextViewNuevoUsuario2);
	    txtImei.setText(settings.getString("ImeiID",null));
	}
	////////////////////////////////////////////////////////LOCATION LISTENER /////////////////////////
	
	public class LocationListener implements android.location.LocationListener
	{
	   // Location mLastLocation;

	     public LocationListener(String provider)
	    {
	    	
	        Log.e(TAG, "[LocationListener] LocationListener Provider " + provider);				//DEBUG
	      //  mLastLocation = new Location(provider);       
	    }
		    /////////////////////////////////////////////////////////////// ONLOCATION CHANGED ///////////////////////////
		    
			@SuppressWarnings("unused")
			public void onLocationChanged(Location location )
		    {
				 Socket sock = null; 
			    	//Log.i(TAG, "[onLocationChanged] onLocationChanged: " + location);					//DEBUG
			    	
			    	// mLastLocation.set(location);
			    	 Log.i(TAG, "[onLocationChanged] SET LOCATION LAST");					//DEBUG
			    	 
			        if(location!=null)
			        {
			        	Log.i(TAG, "[onLocationChanged] LOCATION != NULL");					//DEBUG
				   	  try
				   	  {
				   		  SharedPreferences settings = getSharedPreferences("HT",MODE_PRIVATE);
				
				   		  	Log.i(TAG,"[onLocationChanged] Enviando datos a Server "+"190.18.128.130 : 5123");			//DEBUG
					   		
				   		 try
				   		  {
					   		/*
					   		   	
					   		 sock = new Socket("190.18.128.130",5123);
					   		sock.setSoTimeout(5000);
					   		*/					   							   		
					   		SocketAddress sockaddr = new InetSocketAddress("190.18.128.130",5123);
					   		sock = new Socket();
					   		sock.connect(sockaddr, 5000);
				   		  }catch(Exception ex)
				   		  {
				   			Log.e(TAG,"[onLocationChanged] NO SE CONECTO EL SOCKET: "+ex);			//DEBUG
				   			return;
				   		  }	
				   		 if(sock!=null)
				   		 {
					   		Log.i(TAG,"[onLocationChanged] CONEXION SOCKET CREADA ");			//DEBUG   		
					   		Log.i(TAG,"[onLocationChanged] SOCKET IP: "+String.valueOf(sock.getLocalPort()));			//DEBUG
					   		Log.i(TAG,"[onLocationChanged] SOCKET PORT: "+String.valueOf(sock.getLocalPort()));			//DEBUG
					   		Log.i(TAG,"[onLocationChanged] SOCKET IS CONNECTED?: "+String.valueOf(sock.isConnected()));			//DEBUG
					   		//Log.i(TAG,"[onLocationChanged] SOCKET ADDRESS Local: "+String.valueOf(sock.getLocalSocketAddress()));			//DEBUG	   		
					   		Log.i(TAG,"[onLocationChanged] SOCKET ADDRESS Remote: "+String.valueOf(sock.getRemoteSocketAddress()));			//DEBUG
					   		
					   		 dbLat=location.getLatitude();
					   		 dbLon=location.getLongitude();
					   		 dbAlt=location.getAltitude();
					   		 flSpeed=location.getSpeed();
					   		
					   		  String test = "{"
					   				  		+ "\"Id\":\""+"AndCYS"+"\","
					   				  		+ "\"Lat\":\""+String.valueOf(dbLat)+"\","
					   				  		+ "\"Lng\":\""+String.valueOf(dbLon)+"\","
					   				  		+ "\"Alt\":\""+String.valueOf(dbAlt)+"\","
					   				  		+ "\"Spe\":\""+String.valueOf(flSpeed)+"\","						
					   				  		+ "\"IMEI\":\""+Imei+"\","
					   				  		+ "\"CodAct\":\""+settings.getString("CodeActiv",null)+"\","
					   				  		+ "\"Batt\":\""+ strLevelbat+"\""
					   		  				+ "}";
					   		  
					   		  Log.i(TAG,"[onLocationChanged] Stream enviado: "+test);					//DEBUG
					   		  
					   		  sock.getOutputStream().write(test.getBytes());
					   		  
					   		  sock.getOutputStream().flush();
					   		  sock.close();  			   		
				   		 }else
				   		 {
				   			Log.e(TAG, " [onLocationChanged] Error enviando al socket NULL ");
				   			return;
				   		 }
					  /*}catch(Exception ex)
				   	  {
				   	      Log.e(TAG, " [onLocationChanged] Error enviando al socket: "+ex.getMessage());			//DEBUG   	     
				   	      try {
							sock.close();
						  }catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						  }
				   	  }*/					  
				   	  }catch(UnknownHostException Exu)
				   	  {
				   		Log.e(TAG, " [onLocationChanged] Error enviando al socket: "+Exu.getMessage());
				   	      try {
				   	    	sock.getOutputStream().flush();
							sock.close();
							//////////////////////////////////////////////////////////////
							Intent myIntent=null;
					    	try
					       	{
					    		 myIntent=new Intent(getApplicationContext(),HTService.class);
					    		
					       	}catch(Exception ex)
					         {
					        	 Log.e("PositionCYSActivity","[onCreate] ERROR I EX: "+ex);		        
					         }
					       	try
					       	{
					       		startActivity(myIntent);
					         }catch(Exception ex)
					         {
					        	 Log.e("PositionCYSActivity","[onCreate] ERROR A EX: "+ex);
					         }
							//////////////////////////////////////////////////////////////////
						  }catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						  }
				   	  }catch(IOException Exi)
				   	  {
				   		Log.e(TAG, " [onLocationChanged] Error enviando al socket: "+Exi.getMessage());
				   	      try {
				   	    	sock.getOutputStream().flush();
							sock.close();
							
						  }catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						  }
				   	      //////////////////////////////////////////////////////////////
				   	   Intent myIntent=null;
				    	try
				       	{
				    		 myIntent=new Intent(getApplicationContext(),HTService.class);
				    		
				       	}catch(Exception ex)
				         {
				        	 Log.e("PositionCYSActivity","[onCreate] ERROR I EX: "+ex);		        
				         }
				       	try
				       	{
				       		startActivity(myIntent);
				         }catch(Exception ex)
				         {
				        	 Log.e("PositionCYSActivity","[onCreate] ERROR A EX: "+ex);
				         }
				       	/////////////////////////////////////////////////////////////////////
				   	  }
			        
		        }else
		        {	
		        	if(sock!=null)
		        	{
		        		try {
							sock.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		        	}
		        	Log.e(TAG, " [onLocationChanged] Location NULL");			//DEBUG
		        }
		   	  try
		   	  {
		   		//objPositioncys.updateCoordinates(dbLat,dbLon,dbAlt,flSpeed,Imei,strLevelbat);
		   	  }catch(Exception ex)
		   	  {
		   		  Log.i(TAG,"[onLocationChanged] ERROR Update Coordenadas en TELA: "+ex );
		   	  }
		    }
		    public void onProviderDisabled(String provider)
		    {
		    	/*if(provider.equals("gps"))
		    	{
		            //Toast.makeText(getApplicationContext(), "GPS is off", Toast.LENGTH_LONG).show();
		            startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
		        }*/		    	
		        Log.e(TAG, "[onProviderDisabled] onProviderDisabled: " + provider);					//DEBUG            
		    }
		    
		    public void onProviderEnabled(String provider)
		    {
		        Log.e(TAG, "[onProviderEnabled] onProviderEnabled: " + provider);					//DEBUG
		    }
		    public void onStatusChanged(String provider, int status, Bundle extras)
		    {
		        Log.e(TAG, "[onStatusChanged] onStatusChanged: " + provider);						//DEBUG
		    }
		    
		    protected void onDestroy() {
		        stopListening();
		        onDestroy();
		    }
	
		    protected void onPause() {
		        stopListening();
		        onPause();
		    }
	
		    protected void onResume() {
		        startListening();
		        onResume();
		    }
		    /**********************************************************************
		     * helpers for starting/stopping monitoring of GPS changes below 
		     **********************************************************************/
		    private void startListening() {
		    	mLocationManager.requestLocationUpdates(
		            LocationManager.GPS_PROVIDER, 
		            0, 
		            0, 
		            this
		        );
		    }
	
		    private void stopListening() {
		        if (mLocationManager != null)
		        	mLocationManager.removeUpdates(this);
		    }
	    
	    
	} 
	
	///////////////////////////////////////////////////////////////////////////////////////////////////
	
	 LocationListener[] mLocationListeners = new LocationListener[] 
	 {  
	 
			new LocationListener(LocationManager.GPS_PROVIDER),
	        new LocationListener(LocationManager.NETWORK_PROVIDER)
	};
	

	///////////////////////////////////////////onRestart///////////////////////////////////////////////////////////
	 @Override
	 protected void onRestart() {
	     super.onRestart();  // Always call the superclass method first
	     
	 	Intent myIntent=null;
    	try
       	{
    		//myIntent = new Intent(cont, HTService.class);
    		
    		 myIntent=new Intent(this.getApplicationContext(),HTService.class);
	    		
	       	}catch(Exception ex)
	         {
	        	 Log.e("PositionCYSActivity","[onCreate] ERROR I EX: "+ex);		        
	         }	    	
	       	try
	       	{
	       		startActivity(myIntent);
	         }catch(Exception ex)
	         {
	        	 Log.e("PositionCYSActivity","[onCreate] ERROR A EX: "+ex);
	         }
	     // Activity being restarted from stopped state    
	 }
	 
	//////////////////////////////////////////////////////////////////////////////////////////////////////
	public void initializeLocationManager() 
	{
	   Log.e(TAG, "[initializeLocationManager] initializeLocationManager");				//DEBUG
	   
	    if (mLocationManager == null) {
	    	Log.e(TAG, "[initializeLocationManager] mLocationManager == NULL");				//DEBUG
	    	mLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
	    }
	   // mLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
	    
	    if (mTelephoneManager == null)
	    {
	    	Log.e(TAG, "[initializeLocationManager] mTelephoneManager==NULL");				//DEBUG
	    	mTelephoneManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
	    }
	   // mTelephoneManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
	}
	
	//////////////////////////////////////////////// BATTERY &////////////////////////////////////////
	public String strbatteryLevel() {
		
		BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
			
			public void onReceive(Context context, Intent intent) {
		
				context.unregisterReceiver(this);
			
				int rawlevel = intent.getIntExtra("level", -1);
			
				int scale = intent.getIntExtra("scale", -1);
			
				int levelbat = -1;
			
				if (rawlevel >= 0 && scale > 0) {
			
					levelbat = (rawlevel * 100) / scale;
			
				}
				//Log.i(TAG, "[strbatteryLevel] BATTERY int: " + levelbat);
				strLevelbat=String.valueOf(levelbat);
				Log.i(TAG, "[strbatteryLevel] BATTERY str: " + strLevelbat);	
			}
			
		};
		
		IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);    	
		registerReceiver(batteryLevelReceiver, batteryLevelFilter);
		Log.i(TAG, "[strbatteryLevel] BATTERY str final: " + strLevelbat);	
		
		return strLevelbat;
	}	
	
	///////////////////////////////////////////////////////////////////////////////////////////
	public IBinder onBind(Intent arg0)
	{
	    return null;
	}
	
	
	
}
